<template>
  <div>
    <!-- 弹框 -->
    <el-button plain @click="dialogVisible" type="primary">新增</el-button>
    <el-dialog v-model="popbox" :title="ruleForm.id ? '编辑' : '添加'" width="500" :before-close="handleClose">
      <el-form ref="ruleFormRef" :rules="rules" style="max-width: 400px" :model="ruleForm" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="体系选择:" prop="id">
          <el-select v-model="ruleForm.pid" placeholder="知识章节">
            <el-option v-for="item in listArr" :key="item.key" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="名称:" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <!-- <el-form-item label="知识点数量:" prop="code">
          <el-input v-model="ruleForm.code" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="define">确定</el-button>
          <el-button type="primary" @click="popbox = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-table :data="tableData" border style="width: 100%" row-key="id" :tree-props="{ children: 'children' }"
      default-expand-all>
      <el-table-column align="center" type="index" label="序号" width="55" :index="indexMethod" />
      <el-table-column align="center" prop="name" label="名称" width="360" />
      <!-- <el-table-column align="center" prop="pid" label="id" width="180" /> -->
      <el-table-column align="center" prop="code" label="知识点数量" />
      <el-table-column align="center" label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="revise(row)" plain>
            修改
          </el-button>
          <el-button size="small" @click="erase(row.id)" plain>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>


<script lang="ts" setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessageBox, ElMessage, FormRules, FormInstance } from 'element-plus'
import { inquiry, remove, editor } from '@/api/knowledgeSystem/system'
// const editdata = ref('新增')
let popbox: any = ref(false)
//添加数据
let tableData = ref([])
interface RuleForm {
  id: String,
  name: String,
  code: String,
  pid?: Number,
  remark: string,
  hasChildren?: boolean
  children?: RuleForm[]
}
const a = () => {
  return {
    id:'',
    name: '',
    code: '',
    pid: '',// 默认为o id是不可选自增的
    remark: ''
  }
}
const ruleForm = reactive<RuleForm>(a())
//表单效验
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})
const listArr = ref()
const data: any = reactive({
  pageNo: 1,
  pageSize: 100
})
//封装数据默认显示
const setlistArr = (data:{name:string,pid:number,id:number}[])=>{
  listArr.value = data.map((item)=>{
    return{
      label:item.name,
      value:item.id,
      key:item.id
    }
  })
}
const DefaultDisplay = async () => {
  let sartch: any = await inquiry(data)
  console.log(sartch,'sartch');
  setlistArr(sartch)
  tableData.value = sartch
  // let newTableList = [];
  // let existingItem = {}
  // let hashTable: { [key: string]: any } = {};
  // console.log(hashTable);

  // let arr = [...sartch.list];

  // // 对数据进行处理
  // arr.forEach((item, index) => {
  //   newTableList.push(item);
  //   hashTable[item.id] = item;

  //  console.log(hashTable[item.id]);
  //   existingItem = hashTable[item.id];
  //   console.log(existingItem);
  //   if (existingItem) {
  //     if (!existingItem.children) {
  //       existingItem.children = [];
  //     }
  //     existingItem.children.push(item); // 将当前项添加到父项的 children 中
  //   }
  // });

  // // 打印处理后的数据
  // console.log(existingItem)
}
onMounted(() => {
  DefaultDisplay()
})
//知识体系添加
const dialogVisible = () => {
  popbox.value = true
  ruleForm.name = ''
}

const selectOptions = ref([])
const ruleFormRef = ref<FormInstance>()
// 添加一个函数，用于根据pid值查找对应的节点
const findNodeById = (id: number) => {
  return selectOptions.value.find(option => option.value === id)
}

// 添加一个函数，用于判断节点是否是父节点
const isParentNode = (node: any) => {
  // 在这里你可以根据你的数据结构定义判断父节点的逻辑，比如判断是否有子节点
  return node.children && node.children.length > 0
}

// 定义一个函数，用于将节点添加到selectOptions中
const addToSelectOptions = (node: any) => {
  if (isParentNode(node)) {
    // 如果是父节点，则将其添加到selectOptions中
    selectOptions.value.push({ value: node.id, label: node.name, isParent: true })
  } else {
    // 如果是子节点，则找到对应的父节点，将其添加到父节点的children中
    const parentNode = findNodeById(node.pid)
    if (parentNode) {
      if (!parentNode.children) {
        parentNode.children = [] 
      }
      parentNode.children.push({ value: node.id, label: node.name })
    }
  }
}

const define = async () => {
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 表单验证通过，继续执行其他逻辑
      // selectOptions.value.push({ value: ruleForm.pid, label: ruleForm.name });
      // addToSelectOptions({ id: ruleForm.pid, name: ruleForm.name, pid: ruleForm.parentId }) // 假设parentId为父节点的id
      // let parentNode = selectOptions.value.find(
      //   (item) => item.value === ruleForm.pid
      // );
      // if (parentNode) {
      //   // 确保 `children` 属性存在
      //   if (!Array.isArray(parentNode.children)) {
      //     parentNode.children = [];
      //   }这部分逻辑没用了 按照那个需求的话 这块的话 怎么说呢 就是我知道怎么做但是接口就一个对吧 不管是加子节点还是新增 
      // }
      // // 添加子节点
      // parentNode.children.push({
      //   value: ruleForm.pid, // 或其他合适的唯一标识符
      //   label: ruleForm.name,
      // });
      // console.log(parentNode);
      console.log(ruleForm)
      editor(ruleForm).then(result => {
        if (result) {
          ElMessage({
            type: "success",
            message: ruleForm.id ? '修改成功' : '添加成功'
          });
          DefaultDisplay();
        } else {
          ElMessage({
            type: "error",
            message: ruleForm.id ? '修改失败' : '添加失败'
          });
        }
        popbox.value = false;
      });
    } else {
      // 表单验证失败，提示用户
      ElMessage.error('请填写正确的表单信息');
    }
  });
}
//知识体系删除
const erase = async (id: number) => {
  ElMessageBox.confirm('确定删除该项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 用户点击了确认按钮
    let rest: any = await remove(id);
    console.log(rest);
    if (rest) {
      ElMessage({
        type: "success",
        message: '删除成功'
      });
      DefaultDisplay();
    } else {
      ElMessage({
        type: "error",
        message: '删除失败'
      });
    }
  }).catch(() => {
    // 用户点击了取消按钮
    console.log('取消删除');
  });
}
//知识体系修改
const revise = async (row: any) => {
  //打开loding弹窗
  popbox.value = true
  //回显数据
  Object.assign(ruleForm, row)

}
const indexMethod = (index: number) => {
  return index + 1
}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认要关闭吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
</script>

<style scoped lang="scss"></style>